import React, { Component } from 'react';
import { Tooltip, message, Switch } from 'antd';
import './index.css';
import BsinBpmnView from '../../BsinBpmnView';
import { saveModelXML } from '../../../services/modelDefinition';

class EditorToolbar extends Component {
  state = {
    modeler: null,
    scale: 1,
    svgVisible: 'none',
    svgSrc: '',
    issimulation: false,
  };

  componentDidMount() {
    setTimeout(() => {
      const { modeler } = this.props;
      this.setState({
        modeler: modeler,
      });
    });
  }

  /**
   * 前进操作
   */
  handleRedo = () => {
    this.state.modeler.get('commandStack').redo();
  };

  /**
   * 撤销操作
   */
  handleUndo = () => {
    this.state.modeler.get('commandStack').undo();
  };

  /**
   * 流程图放大缩小
   */
  handleZoom = (radio) => {
    return () => {
      const newScale = !radio
        ? 1.0 // 不输入radio则还原
        : this.state.scale + radio <= 0.2 // 最小缩小倍数
        ? 0.2
        : this.state.scale + radio;
      this.state.modeler.get('canvas').zoom(newScale);
      this.setState({
        scale: newScale,
      });
    };
  };

  /**
   * 保存xml
   */
  handleSaveXml = () => {
    this.state.modeler.saveXML({ format: true }, async (err, data) => {
      const { editModel } = this.props;
      let res = await saveModelXML({
        id: editModel.id,
        updatedBy: 'admin',
        bpmnModelXml: data,
        isNewVersion: true,
      });
      if (res.code == '000000') {
        message.success('保存流程图成功');
      } else {
        message.error('保存流程图失败');
      }
    });
  };

  /**
   * 下载Bpmn文件
   */
  handleDownloadSvg = () => {
    this.state.modeler.saveSVG({ format: true }, (err, data) => {
      this.download('svg', data);
    });
  };

  /**
   * 下载 XML 格式
   */
  handleDownloadXml = () => {
    this.state.modeler.saveXML({ format: true }, (err, data) => {
      this.download('xml', data);
    });
  };

  download = (type, data, name) => {
    let dataTrack = '';
    const a = document.createElement('a');
    switch (type) {
      case 'xml':
        dataTrack = 'bpmn';
        break;
      case 'svg':
        dataTrack = 'svg';
        break;
      default:
        break;
    }
    name = name || `diagram.${dataTrack}`;
    a.setAttribute(
      'href',
      `data:application/bpmn20-xml;charset=UTF-8,${encodeURIComponent(data)}`,
    );
    a.setAttribute('target', '_blank');
    a.setAttribute('dataTrack', `diagram:download-${dataTrack}`);
    a.setAttribute('download', name);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  };

  /**
   * 预览图片
   */
  handlePreview = () => {
    this.state.modeler.saveSVG().then((data) => {
      this.setState({
        svgSrc: data,
        svgVisible: 'block',
      });
    });
  };

  /**
   * 模拟功能
   */

  simulation = () => {
    this.state.modeler.get('toggleMode').toggleMode();
    const { issimulation } = this.state;
    this.setState({ issimulation: !issimulation });
  };

  /**
   * 关闭模态 用于子组件
   */
  handlePreviewOfClose = () => {
    this.setState({ svgVisible: 'none' });
  };
  render() {
    const { svgVisible, svgSrc, issimulation } = this.state;
    return (
      <div>
        <ul className="workflow-ui-editorToolbar">
          <Tooltip
            title={issimulation ? '退出' : '模拟'}
            placement="bottom"
            color="#108ee9"
          >
            <li className="workflow-ui-simulation" onClick={this.simulation}>
              <Switch checkedChildren="退出" unCheckedChildren="模拟" />
            </li>
          </Tooltip>
          <Tooltip title="打开BPMN文件" placement="bottom" color="#108ee9">
            <li>
              <label>
                <div
                  className="workflow-ui-openIt"
                  onClick={this.handleOpenFile}
                ></div>
                <input type="file" style={{ display: 'none' }} />
              </label>
            </li>
          </Tooltip>
          <Tooltip title="撤销" placement="bottom" color="#108ee9">
            <li className="workflow-ui-undo" onClick={this.handleUndo}></li>
          </Tooltip>
          <Tooltip title="恢复" placement="bottom" color="#108ee9">
            <li className="workflow-ui-redo" onClick={this.handleRedo}></li>
          </Tooltip>
          <Tooltip title="重置大小" placement="bottom" color="#108ee9">
            <li className="workflow-ui-zoom" onClick={this.handleZoom()}></li>
          </Tooltip>
          <Tooltip title="放大" placement="bottom" color="#108ee9">
            <li
              className="workflow-ui-zoomIn"
              onClick={this.handleZoom(0.1)}
            ></li>
          </Tooltip>
          <Tooltip title="缩小" placement="bottom" color="#108ee9">
            <li
              className="workflow-ui-zoomOut"
              onClick={this.handleZoom(-0.1)}
            ></li>
          </Tooltip>
          <Tooltip title="保存流程" placement="bottom" color="#108ee9">
            <li className="workflow-ui-save" onClick={this.handleSaveXml}></li>
          </Tooltip>
          <Tooltip title="下载Bpmn文件" placement="bottom" color="#108ee9">
            <li
              className="workflow-ui-download"
              onClick={this.handleDownloadXml}
            ></li>
          </Tooltip>
          <Tooltip title="下载流程文件" placement="bottom" color="#108ee9">
            <li
              className="workflow-ui-image"
              onClick={this.handleDownloadSvg}
            ></li>
          </Tooltip>
          <Tooltip title="预览" placement="bottom" color="#108ee9">
            <li
              className="workflow-ui-preview"
              onClick={this.handlePreview}
            ></li>
          </Tooltip>
        </ul>
        <BsinBpmnView
          isclose={svgVisible}
          handlePreviewOfClose={this.handlePreviewOfClose}
        >
          <div
            dangerouslySetInnerHTML={{
              __html: svgSrc.svg,
            }}
          />
        </BsinBpmnView>
      </div>
    );
  }
}

export default EditorToolbar;
